//
//  UUDriverVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 23/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUDriverVC.h"
#import "UUBaseTableViewCell.h"
#import "UUResourceManager.h"
#import "UUDriverEditVC.h"
#import "UUDriverManager.h"
#import "UUFleetManager.h"
#import "UUPermissionManager.h"

@interface UUDriverCell : UUBaseTableViewCell

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *mobileLabel;
@property (nonatomic, strong) UILabel *fleetLabel;

@end

@implementation UUDriverCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.nameLabel = [UILabel new];
        self.nameLabel.font = [UIFont systemFontOfSize:16];
        [self.contentView addSubview:self.nameLabel];
        [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(14);
            make.top.mas_equalTo(16);
        }];
        
        self.mobileLabel = [UILabel new];
        self.mobileLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:self.mobileLabel];
        [self.mobileLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.nameLabel.mas_left);
            make.top.equalTo(self.nameLabel.mas_bottom).offset(15);
        }];
        
        self.fleetLabel = [UILabel new];
        self.fleetLabel.font = [UIFont systemFontOfSize:15];
        self.fleetLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
        [self.contentView addSubview:self.fleetLabel];
        [self.fleetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.nameLabel.mas_top);
            make.right.mas_equalTo(-15);
        }];
    }
    return self;
}

@end

////////////////////////////////////////////////////////////

@interface UUDriverVC () <UITableViewDataSource, UITableViewDelegate, UUDriverManagerProtocol>

@property (nonatomic, strong) NSArray<NSNumber *> *drivers;

@end

@implementation UUDriverVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView.backgroundColor = COMMON_BACKGROUND_COLOR;
    [self.tableView registerClass:[UUDriverCell class] forCellReuseIdentifier:@"Cell"];
    
    if (self.didSelectDriverBlock == nil && [GetPermissionManager() checkPermission:UUPermissionFlagDriverReadWrite]) {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:GetResourceManager().addIconText
                                                                                  target:self
                                                                                selector:@selector(addDriver:)];
    }
    
    [self reloadDrivers];
    
    [GetDriverManager() addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private methods

- (IBAction)addDriver:(id)sender {
    UUDriverEditVC *editVC = [UUDriverEditVC instanceOfAppropriate];
    editVC.editable = YES;
    [self.navigationController pushViewController:editVC animated:YES];
}

- (void)reloadDrivers {
    self.drivers = [GetDriverManager() fetchDriversForFleetId:self.fleetId];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.drivers.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUDriverCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    NSNumber *driverId = self.drivers[indexPath.row];
    UUDriverModel *driverModel = [GetDriverManager() fetchDriverWithDriverId:driverId];
    
    cell.nameLabel.text = driverModel.name;
    cell.mobileLabel.text = driverModel.mobile;
    
    UUFleetModel *fleetModel = [GetFleetManager() fetchFleetWithFleetId:driverModel.fleetId];
    cell.fleetLabel.text = fleetModel.name;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSNumber *driverId = self.drivers[indexPath.row];
    
    if (self.didSelectDriverBlock == nil) {
        UUDriverEditVC *editVC = [UUDriverEditVC instanceOfAppropriate];
        editVC.driverId = driverId;
        [self.navigationController pushViewController:editVC animated:YES];
    } else {
        self.didSelectDriverBlock(driverId);
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.didSelectDriverBlock == nil && [GetPermissionManager() checkPermission:UUPermissionFlagDriverReadWrite];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [UIAlertController presentAlertControllerWithTitle:@"确定删除该司机吗？" message:nil doneBlock:^{
            NSNumber *driverId = self.drivers[indexPath.row];
            
            ShowIndicator();
            WEAK_SELF();
            [GetDriverManager() asyncDeleteDriverWithDriverId:driverId completeBlock:^(NSError *error) {
                HideIndicatorInView(weakSelf.view);
                
                if (error != nil) {
                    ShowTipsOnView(error.localizedDescription, weakSelf.view);
                }
            }];
        } cancelBlock:nil];
    }
}

#pragma mark - UUDriverManagerProtocol methods

- (void)driverManagerDidUpdateDrivers {
    [self reloadDrivers];
}

- (void)driverManagerDidDeleteDrivers:(NSArray<NSNumber *> *)drivers {
    if (self.drivers.count > 0) {
        NSMutableArray<NSIndexPath *> *indexPathes = [NSMutableArray array];
        NSMutableIndexSet *indexSet = [NSMutableIndexSet new];
        for (int j = 0; j < drivers.count; ++j) {
            for (int i = 0; i < self.drivers.count; ++i) {
                if ([self.drivers[i] isEqual:drivers[j]]) {
                    [indexPathes addObject:[NSIndexPath indexPathForRow:i inSection:0]];
                    [indexSet addIndex:i];
                    break;
                }
            }
        }
        
        NSMutableArray<NSNumber *> *mutableDrivers = [self.drivers mutableCopy];
        [mutableDrivers removeObjectsAtIndexes:indexSet];
        self.drivers = mutableDrivers;
        [self.tableView deleteRowsAtIndexPaths:indexPathes
                              withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

@end
